package com.tzy.rpc.transport.netty.client;/**
 * @description:
 * @Author HP
 * @create 2022/3/18 17:18
 */

import com.tzy.rpc.entity.RpcResponse;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author HP
 * @create 2022-03-18 17:18
 * @desc 未处理的请求（对所有客户端请求进行统一管理）
 **/
public class UnprocessedRequests {
    /**
     * key为请求ID，value为创建的CompletableFuture实例
     */
    private static ConcurrentHashMap<String, CompletableFuture<RpcResponse>> unprocessedResponseFutures = new ConcurrentHashMap<>();

    public void put(String requestId, CompletableFuture<RpcResponse> future) {
        unprocessedResponseFutures.put(requestId, future);
    }

    public void remove(String requestId) {
        unprocessedResponseFutures.remove(requestId);
    }

    public void complete(RpcResponse rpcResponse) {
        CompletableFuture<RpcResponse> future = unprocessedResponseFutures.remove(rpcResponse.getRequestId());
        if (null != future) {
            future.complete(rpcResponse);
        } else {
            throw new IllegalStateException();
        }
    }

}
